package com.hyjx.framework.component.upload;

import com.hyjx.framework.common.CommonUtil;
import com.hyjx.framework.common.util.DocToPDFConverter;
import com.hyjx.framework.common.util.StringHelper;
import com.hyjx.framework.orm.dao.IBaseDao;
import com.hyjx.framework.orm.dao.Pager;
import com.hyjx.framework.service.ConfigManager;
import com.hyjx.framework.service.UserCenterService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.UUID;

/**
 * 附件上传服务实现类
 *
 * @author dijian
 */
@Service("uploadService")
@Transactional
public class UploadServiceImpl implements UploadService {
    
    @Resource
    private IBaseDao dao;
    
    private final String MODULE = new UploadModel().getModuleName();
    
    public IBaseDao getDao() {
        return dao;
    }
    
    public void setDao(IBaseDao dao) {
        this.dao = dao;
    }
    
    /**
     * 查询数据
     *
     * @param model
     * @return
     */
    @Override
    public String queryList(Object model) {
        Pager pager = dao.getPager(MODULE + ".queryList", MODULE + ".queryCount", model);
        return CommonUtil.getPageJsonStr(pager);
    }
    
    @Override
    public boolean add(MultipartHttpServletRequest request, HttpServletResponse response) {
        boolean flag1 = false;
        boolean flag2 = true;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
            String businessId = request.getParameter("vchr_entityid") == null ? "" : request.getParameter("vchr_entityid");
            String vchr_domain = request.getParameter("vchr_domain") == null ? "" : request.getParameter("vchr_domain");
            String fileType = request.getParameter("fileType") == null ? "" : request.getParameter("fileType");
            Iterator<String> iterator = request.getFileNames();
            while (iterator.hasNext()) {
                String fileName = iterator.next();
                MultipartFile multipartFile = request.getFile(fileName);
                String filename = multipartFile.getOriginalFilename();
                String uuid = UUID.randomUUID().toString();
                String fileTypeName = filename.substring(filename.lastIndexOf("."), filename.length());
                String fileTransName = uuid + fileTypeName;
                String path = null;
                
                if ("1".equals(fileType)) {
                    path = ConfigManager.getAttatchmentsPicPath() + File.separator + vchr_domain + File.separator + businessId + File.separator;
                } else {
                    path = ConfigManager.getAttatchmentsPath() + File.separator + vchr_domain + File.separator + businessId + File.separator;
                }
                File upload = new File(path);
                if (!upload.exists())
                    upload.mkdirs();
                File source = new File(path + fileTransName);
                multipartFile.transferTo(source);
                
                String x = request.getParameter("x") == null ? "" : request.getParameter("x");
                String y = request.getParameter("x") == null ? "" : request.getParameter("y");
                String w = request.getParameter("x") == null ? "" : request.getParameter("w");
                String h = request.getParameter("x") == null ? "" : request.getParameter("h");
                String srcImagePath = path + fileTransName;
                if (x != "") {
                    int imageX = Integer.parseInt(x);
                    int imageY = Integer.parseInt(y);
                    int imageH = Integer.parseInt(h);
                    int imageW = Integer.parseInt(w);
                    CutImgUtil.imgCut(srcImagePath, imageX, imageY, imageW, imageH);
                }
                ///插入附件信息到pub_attachments表
                UploadModel model = new UploadModel();
                model.setVchr_uploaduser(UserCenterService.getCurrentUserInfo().getUser_account());
                model.setVchr_uploaduserid(UserCenterService.getCurrentUserId());
                model.setVchr_id(StringHelper.getPrimaryKey());
                model.setDate_uploaddate(StringHelper.getDateTime());
                model.setLastdate(StringHelper.getDateTime());
                model.setNum_filesize(String.valueOf(multipartFile.getSize()));
                model.setVchr_entityid(businessId);
                model.setVchr_domain(vchr_domain);
                model.setVchr_originname(filename);
                model.setVchr_storagename(fileTransName);
                //service.add(model);
                flag1 = dao.addObject(MODULE + ".insert", model);
            /*
			 * 生成缩略图，并且保存缩略图
			 */
                if (filename.indexOf("flv") >= 0 || filename.indexOf("mp4") >= 0) {
                    String imagePath = ConfigManager.getAttatchmentsPath() + vchr_domain + File.separator + businessId + File.separator;
                    model.setVchr_id(StringHelper.getPrimaryKey());
                    model.setDate_uploaddate(StringHelper.getDateTime());
                    model.setLastdate(StringHelper.getDateTime());
                    model.setVchr_originname(model.getVchr_originname() + "对应视频图片");
                    
                    VideoThumbTaker videoThumbTaker = new VideoThumbTaker("D:\\ffmpeg-20161025-c117343-win64-static\\bin\\ffmpeg.exe");
                    File f = new File(imagePath);
                    if (!f.exists())
                        f.mkdirs();
                    videoThumbTaker.getThumb(path + fileTransName, imagePath + uuid + ".PNG", 800, 600, 0, 0, 30);
                    model.setVchr_storagename(uuid + ".PNG");
                    //service.add(model);
                    flag2 = dao.addObject(MODULE + ".insert", model);
                }
                if (!StringUtils.isEmpty(vchr_domain) && vchr_domain.equals("ckeditor")) {
                    String callback = request.getParameter("CKEditorFuncNum");
                    response.getWriter().println("<script type=\"text/javascript\">");
                    String path2 = request.getContextPath();
                    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path2 + "/";
                    response.getWriter().println("window.parent.CKEDITOR.tools.callFunction(" + callback
                            + ",\'" + basePath + "upload/getPreview.xhtml?vchr_entityid=" + businessId + "&vchr_domain=" + vchr_domain + "&fileName=" + fileTransName + "\',\'\');");
                    response.getWriter().println("</script>");
                    //upload/getPreview.xhtml?vchr_entityid=ckeditor&vchr_domain=ckeditor&fileName=4b33a306-8825-4c46-a72e-a66944888b3b.jpg
                }
                //else
                //response.getWriter().print(File.separator+vchr_domain+File.separator+businessId+File.separator+fileTransName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return flag1 && flag2;
        
        //return dao.addObject("upload.insert", model);
    }
    
    @Override
    public UploadModel getInfoById(String s) {
        UploadModel model = null;
        model = (UploadModel) dao.queryObject(MODULE + ".getInfoById", s);
        return model;
    }
    
    @Override
    public int delete(String ids) {
        String[] id_array = ids.split(",");
        int num = 0;
        for (String id : id_array) {
            UploadModel model = getInfoById(id);
            String path = ConfigManager.getAttatchmentsPath() + (model.getVchr_domain() == null ? "" : model.getVchr_domain()) + File.separator + (model.getVchr_entityid() == null ? "" : model.getVchr_entityid()) + File.separator + model.getVchr_storagename();
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            } else {
                path = ConfigManager.getAttatchmentsPicPath() + (model.getVchr_domain() == null ? "" : model.getVchr_domain()) + File.separator + (model.getVchr_entityid() == null ? "" : model.getVchr_entityid()) + File.separator + model.getVchr_storagename();
                file = new File(path);
                file.delete();
            }
            
            dao.deleteObject(MODULE + ".delete", id);
            num++;
        }
        return num;
    }
    
    @Override
    public UploadModel getUploadModelByStorageName(String storageName) {
        return (UploadModel) dao.queryObject(MODULE + ".selectByStorageName", storageName);
    }
    
    @Override
    public String download(HttpServletRequest request,
                           HttpServletResponse response) {
        String ids = request.getParameter("id");
        String fileType = request.getParameter("fileType");
        String businessId = request.getParameter("vchr_entityid");
        String vchr_domain = request.getParameter("vchr_domain");
        UploadModel model = (UploadModel) this.getInfoById(ids);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/x-download");
        String filepath = null;
        if ("1".equals(fileType)) {
            filepath = ConfigManager.getAttatchmentsPicPath() + File.separator + vchr_domain + File.separator + businessId + File.separator + model.getVchr_storagename();
        } else {
            filepath = ConfigManager.getAttatchmentsPath() + File.separator + vchr_domain + File.separator + businessId + File.separator + model.getVchr_storagename();
        }
        if (!new File(filepath).exists())
            try {
                response.getWriter().write("<script>alert('文件不存在');close();</script>");
                return null;
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(model.getVchr_originname().getBytes(), "ISO8859-1"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        java.io.OutputStream outp = null;
        java.io.FileInputStream in = null;
        try {
            outp = response.getOutputStream();
            in = new java.io.FileInputStream(new File(filepath));
            byte[] b = new byte[1024];
            int i = 0;
            while ((i = in.read(b)) > 0) {
                outp.write(b, 0, i);
            }
            outp.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return null;
    }
    
    @Override
    public String view(HttpServletRequest request,
                       HttpServletResponse response) {
        String ids = request.getParameter("id");
        String businessId = request.getParameter("vchr_entityid");
        String vchr_domain = request.getParameter("vchr_domain");
        UploadModel model = (UploadModel) this.getInfoById(ids);
        String typename = model.getVchr_originname();
        typename = typename.substring(typename.lastIndexOf(".") + 1);
        String filepath = ConfigManager.getAttatchmentsPath() + File.separator + vchr_domain + File.separator + businessId + File.separator + model.getVchr_storagename();
        response.setCharacterEncoding("utf-8");
        if (typename.equals("pdf")) {
            response.setContentType("application/pdf");
        } else if (typename.equals("txt")) {
            response.setContentType("text/plain");
        } else if (typename.equals("html")) {
            response.setContentType("text/html");
        } else if (typename.equals("docx") || typename.equals("doc") || typename.equals("xls") || typename.equals("xlsx") || typename.equals("ppt") || typename.equals("pptx")) {
            String sourceFile = ConfigManager.getAttatchmentsPath() + File.separator + vchr_domain + File.separator + businessId + File.separator + model.getVchr_storagename();
            String pdfpath = ConfigManager.getAttatchmentsPath() + File.separator + vchr_domain + File.separator + businessId + File.separator;
            String returnfile = DocToPDFConverter.office2PDF(sourceFile, pdfpath, "");
            if (returnfile.indexOf("fail") != -1) {
                try {
                    response.getWriter().write("文件转换失败");
                    return null;
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            } else {
                filepath = returnfile.substring(0, returnfile.lastIndexOf(","));
                response.setContentType("application/pdf");
            }
        }
        
        if (!new File(filepath).exists())
            try {
                response.getWriter().write("文件不存在");
                return null;
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        
        try {
            response.addHeader("Content-Disposition", "filename=" + new String(model.getVchr_originname().getBytes(), "utf-8"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        
        java.io.OutputStream outp = null;
        java.io.FileInputStream in = null;
        try {
            outp = response.getOutputStream();
            in = new java.io.FileInputStream(new File(filepath));
            byte[] bb = new byte[3];
            in.read(bb);
            in.close();
            if (typename.equals("txt") && (bb[0] != -17 || bb[1] != -69 || bb[2] != -65)) {
                //针对ansi编码的txt处理，如果utf-8编码还得测试
                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filepath), "gbk"));
                String linetext = "";
                String linetext2 = "";
                while ((linetext = reader.readLine()) != null) {
                    linetext += "\n";
                    linetext2 += linetext;
                }
                outp.write(linetext2.getBytes("utf-8"));
            } else {
                java.io.FileInputStream infile = new java.io.FileInputStream(new File(filepath));
                byte[] b = new byte[1024];
                int i = 0;
                while ((i = infile.read(b)) > 0) {
                    outp.write(b, 0, i);
                }
            }
            outp.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    
    @Override
    public void getIcon(String cateogry, HttpServletRequest request,
                        HttpServletResponse response) {
        try {
            
            String fileName = request.getParameter("fileName");
            String vchr_entityid = request.getParameter("vchr_entityid");
            String vchr_domain = request.getParameter("vchr_domain");
            String fileType = null;//request.getParameter("fileType");
            fileType = "image/png";
            if (fileName != null && fileName.endsWith("flv"))
                fileType = "video/flv";
            if (vchr_domain == null || vchr_entityid == null) {
                UploadModel model = new UploadModel();
                model.setVchr_storagename(fileName);
                model = (UploadModel) this.getUploadModelByStorageName(fileName);
                if (model != null)
                    fileName = ConfigManager.getAttatchmentsPicPath() + (model.getVchr_domain() == null ? "" : model.getVchr_domain()) + File.separator +
                            (model.getVchr_entityid() == null ? "" : model.getVchr_entityid()) + File.separator + fileName;
            } else {
                fileName = ConfigManager.getAttatchmentsPicPath() + vchr_domain + File.separator + vchr_entityid + File.separator + fileName;
            }
            File file = new File(fileName);
            if (!file.exists()){
                file = new File(request.getSession().getServletContext().getRealPath("/") + "component/images/noPic.jpg");
            }
			/*// 判断文件是否存在如果不存在就返回默认图标
			if (!(file.exists() && file.canRead())) {
				file = new File(request.getSession().getServletContext().getRealPath("/") + "resource/icons/auth/root.png");
			}*/
            FileInputStream inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            int length = inputStream.read(data);
            inputStream.close();
            response.setContentType(fileType);
            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
            stream.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        
    }
    
    @Override
    public String queryCurrentPics(HttpServletRequest request) {
        String vchr_entityid = request.getParameter("vchr_entityid");
        String vchr_domain = request.getParameter("vchr_domain");
        String fileType = request.getParameter("fileType");
        if ("1".equals(fileType)) {
            UploadModel model = new UploadModel();
            model.setVchr_domain(vchr_domain);
            model.setVchr_entityid(vchr_entityid);
            return this.queryList(model);
        } else {
            return "failure";
        }
        
    }
    
    /**
     * 增加捕获
     *
     * @param request
     * @param response
     * @throws Exception
     */
    public void addCapture(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String outMessage = "";
        String picdata = request.getParameter("picdata");
        String vchr_entityid = request.getParameter("vchr_entityid");
        String vchr_domain = request.getParameter("vchr_domain");
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] picbyte = decoder.decodeBuffer(picdata);
        //String fileName = UUID.randomUUID().toString()+"upload_pic.jpg";
        String fileName = System.currentTimeMillis() + ".jpg";
        String upPath = ConfigManager.getAttatchmentsPicPath() + File.separator + vchr_domain + File.separator + vchr_entityid + File.separator;
        File upload = new File(upPath);
        if (!upload.exists())
            upload.mkdirs();
        UploadModel model = new UploadModel();
        model.setVchr_id(StringHelper.getPrimaryKey());
        model.setDate_uploaddate(StringHelper.getDateTime());
        model.setLastdate(StringHelper.getDateTime());
        model.setNum_filesize("100");
        model.setVchr_entityid(vchr_entityid);
        model.setVchr_domain(vchr_domain);
        model.setVchr_originname(fileName);
        model.setVchr_storagename(fileName);
        dao.addObject(MODULE + ".insert", model);
        FileOutputStream fos = new FileOutputStream(upPath + File.separator + fileName);
        try {
            fos.write(picbyte);
            fos.flush();
            fos.close();
            outMessage = "{\"code\":0,\"info\":\"" + fileName + "\"}";
        } catch (IOException e) {
            e.printStackTrace();
            outMessage = "{\"code\":1,\"message\":\"" + e.toString() + "\"}";
        }
        
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.getOutputStream().write(outMessage.getBytes("utf-8"));
        response.getOutputStream().flush();
        response.getOutputStream().close();
        
    }

}